import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:recipe/global.dart';
import 'package:recipe/http-manager.dart';
import 'package:recipe/main_manager.dart';
import 'package:recipe/utils.dart';

class DetailPage extends StatefulWidget {
  DetailPage({Key key, @required this.id, @required this.cover})
      : super(key: key);
  final String id;
  final String cover;

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  Map detailData = {"default": ''};
  @override
  void initState() {
    recipeDetail().then((res) {
      setState(() => {detailData = res, detailData['cover'] = widget.cover});
    });
    super.initState();
  }

  recipeDetail() async {
    String url = "recipe/${widget.id}/";
    try {
      var response = await HttpUtils.request(url, method: HttpUtils.GET);
      return response;
    } catch (e) {
      print(e);
    }
  }

  List<Widget> renderMaterial(material) {
    List<Widget> list = [
      Row(
        children: [
          Text(
            "配料",
            maxLines: 5,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Global.primaryColor,
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
      SizedBox(height: 10),
    ];
    String materialstr = json.encode(material);
    final _material = json.decode(materialstr);
    List.generate(_material.length, (index) {
      String str = json.encode(_material[index]);
      final item = json.decode(str);
      list.add(
        Container(
          decoration: BoxDecoration(
              color: Global.primaryColor.withOpacity(0.8),
              borderRadius: BorderRadius.circular(5)),
          padding: EdgeInsets.all(3),
          child: Text(
            "${item['name']}/${item['num']}",
            style: TextStyle(
                fontSize: 10, color: Colors.white, fontWeight: FontWeight.w600),
          ),
        ),
      );
    });
    return list;
  }

  List<Widget> renderStep(step) {
    List<Widget> list = [
      SizedBox(height: 10),
      Row(
        children: [
          SizedBox(width: 10),
          Text(
            "做法",
            maxLines: 5,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Global.primaryColor,
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
      SizedBox(height: 10),
    ];
    String stepstr = json.encode(step);
    final _step = json.decode(stepstr);
    List.generate(_step.length, (index) {
      String str = json.encode(_step[index]);
      final item = json.decode(str);
      list.add(
        Container(
          width: MediaQuery.of(context).size.width,
          padding: EdgeInsets.all(2),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Row(
                children: [
                  SizedBox(width: 20),
                  Container(
                    width: MediaQuery.of(context).size.width - 50,
                    child: Text(
                      item['step'],
                      maxLines: 5,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Global.fontColor,
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
              Container(
                width: MediaQuery.of(context).size.width,
                child: ClipRRect(
                  borderRadius: BorderRadius.all(
                    Radius.circular(5),
                  ),
                  child: FadeInImage.assetNetwork(
                    placeholder: 'assets/images/20201014150850.jpg',
                    fadeInDuration: const Duration(milliseconds: 500),
                    image: item['img'],
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);
    return detailData["default"] == ''
        ? Container(
            color: Global.backgroundColor,
            child: Center(child: CircularProgressIndicator()),
          )
        : detailData["recipeId"] != null
            ? Scaffold(
                appBar: AppBar(
                  iconTheme: IconThemeData(color: Global.backgroundColor),
                  toolbarHeight: 50,
                  elevation: 0,
                  title: Text(
                    detailData["title"],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Global.backgroundColor,
                      fontSize: 15,
                    ),
                  ),
                  actions: <Widget>[
                    IconButton(
                      icon: Icon(_mainManager.isOutside(detailData)
                          ? Icons.star_border
                          : Icons.star),
                      tooltip: '收藏',
                      onPressed: () {
                        Utils.showConfirmDialog(
                          context: context,
                          content: _mainManager.isOutside(detailData)
                              ? '收藏成功！'
                              : '取消收藏成功！',
                        );
                        _mainManager.like(detailData);
                      },
                    )
                  ],
                ),
                body: Container(
                  decoration: BoxDecoration(color: Global.backgroundColor),
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.all(10),
                          decoration: BoxDecoration(
                            color: Global.cardBackgroundColor,
                          ),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Container(
                                width: 100,
                                height: 100,
                                child: ClipRRect(
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(5),
                                  ),
                                  child: FadeInImage.assetNetwork(
                                    placeholder:
                                        'assets/images/20201014150850.jpg',
                                    fadeInDuration:
                                        const Duration(milliseconds: 500),
                                    image: widget.cover,
                                  ),
                                ),
                              ),
                              SizedBox(width: 10),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text(
                                      detailData["title"],
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: Global.fontColor,
                                        fontSize: 17,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                    SizedBox(height: 6),
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        detailData["info"][0]["flavour"] != null
                                            ? Text(
                                                "风味：${detailData["info"][0]["flavour"]}",
                                                maxLines: 5,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  color: Global.fontSecondColor,
                                                  fontSize: 12,
                                                  fontWeight: FontWeight.w500,
                                                ),
                                              )
                                            : Container(),
                                        detailData["info"][0]["degree"] != null
                                            ? Text(
                                                "难度：${detailData["info"][0]["degree"]}",
                                                maxLines: 5,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  color: Global.fontSecondColor,
                                                  fontSize: 12,
                                                  fontWeight: FontWeight.w500,
                                                ),
                                              )
                                            : Container(),
                                        detailData["info"][0]["time"] != null
                                            ? Text(
                                                "时长：${detailData["info"][0]["time"]}",
                                                maxLines: 5,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  color: Global.fontSecondColor,
                                                  fontSize: 12,
                                                  fontWeight: FontWeight.w500,
                                                ),
                                              )
                                            : Container(),
                                        detailData["info"][0]["method"] != null
                                            ? Text(
                                                "做法：${detailData["info"][0]["method"]}",
                                                maxLines: 5,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  color: Global.fontSecondColor,
                                                  fontSize: 12,
                                                  fontWeight: FontWeight.w500,
                                                ),
                                              )
                                            : Container(),
                                      ],
                                    )
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                        SizedBox(height: 10),
                        Container(
                          width: MediaQuery.of(context).size.width,
                          padding: EdgeInsets.all(10),
                          decoration: BoxDecoration(
                            color: Global.cardBackgroundColor,
                          ),
                          child: Wrap(
                            spacing: 5,
                            runSpacing: 10,
                            children: renderMaterial(detailData["material"]),
                          ),
                        ),
                        SizedBox(height: 10),
                        Container(
                          width: MediaQuery.of(context).size.width,
                          decoration:
                              BoxDecoration(color: Global.cardBackgroundColor),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: renderStep(detailData["step_word"]),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              )
            : Scaffold(
                body: Container(
                  color: Global.backgroundColor,
                  child: Center(
                    child: Text(
                      "找不到菜谱详情了，看看别的吧！",
                      style: TextStyle(
                        color: Global.fontSecondColor,
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              );
  }
}
